'use strict';

// login controller
app.controller('LoginFormController', ['$scope', '$q', '$http', '$state', '$window', '$translate', 'AuthService', 'appinfo',
    function ($scope, $q, $http, $state, $window, $translate, AuthService, appinfo) {

        // clear old authorization
        AuthService.logout();

        $scope.user = {};
        $scope.authError = null;
        $scope.visible = true;
        $scope.hasNewVersion = false;
        $scope.apkurl = "";
        $scope.needVerifyCode = true;

        var cookieNameKey = "_userName_Key_";
        var codeKey = "";
        var codeLength = 10;
        var random = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

        $scope.login = function () {
            $scope.visible = !$scope.visible;
            return $q(function (resolve, reject) {
                // check whether need check verify code
                var needKey = getNeedKey();
                var needVerifyCodeUrl = AuthService.getRsContext() + "/rest/verifycode/needVerifyCode?verifyKey=" + needKey;
                $http({
                    method: 'GET',
                    url: needVerifyCodeUrl
                }).then(function successCallback(response) {
                    $scope.needVerifyCode = response.data.data[0].need;
                    if ($scope.needVerifyCode) {
                        var accessUrl = AuthService.getRsContext() + "/rest/verifycode/verify?verifyKey="
                            + $scope.user.verifyCodeKey + "&verifyCode=" + $scope.user.verifyCode;
                        $http({
                            method: 'GET',
                            url: accessUrl
                        }).then(function successCallback(response) {
                            console.log("login response ==========", response);
                            var code = response.data.code;
                            if (code != 0) {
                                $scope.authError = $scope.selectLang == "English" ? response.data.enMessage : response.data.message;//$translate.instant("error.verifycode.code" + code);
                                $scope.visible = !$scope.visible;
                                initVerifyCode();
                                return;
                            }
                            if (code == 0) {
                                $scope.processLogin();
                            }
                        }, function errorCallback(response) {
                            $scope.visible = !$scope.visible;
                            $scope.authError = $translate.instant("rest.error.exception");
                            initVerifyCode();
                            reject('Login Failed.');
                        });
                    }
                    else {
                        $scope.processLogin();
                    }
                });
            });
        };

        $scope.processLogin = function () {
            //save username
            if ($scope.user.rememberme) {
                $window.localStorage.setItem(cookieNameKey, $scope.user.username);
            } else {
                $window.localStorage.removeItem(cookieNameKey);
            }
            // login
            AuthService.login(encodeURI($scope.user.username), $scope.user.password).then(function (authenticated) {
                // login success
                $scope.setCurrentUser(AuthService.getLoginfo());
                // check need verify code
                var needKey = getNeedKey();
                $http({
                    method: "GET",
                    url: AuthService.getRsContext() + "/rest/verifycode/clearErrorTimes?verifyKey=" + needKey
                }).then(function successCallback(data1) {
                    $state.go('app.dashboard');
                });
            }, function (err) {
                // fail
                $scope.visible = !$scope.visible;
                $scope.authError = $translate.instant("user.loginError");

                // check need verify code
                var needKey = getNeedKey();
                $http({
                    method: "GET",
                    url: AuthService.getRsContext() + "/rest/verifycode/addErrorTimes?verifyKey=" + needKey
                }).then(function successCallback(data1) {
                    if (data1.data.code == 0) {
                        $scope.needVerifyCode = data1.data.data[0].need;
                    }
                });

                initVerifyCode();
            });
        }

        $scope.refreshVerifyCode = function () {
            initVerifyCode();
        };
        var initVerifyCode = function () {
            if ($scope.needVerifyCode) {
                codeKey = "";
                for (var i = 0; i < codeLength; i++) {
                    var index = Math.floor(Math.random() * 34);
                    codeKey += random[index];
                }
                $scope.user.verifyCode = "";
                codeKey = codeKey + (new Date()).getTime();
                $scope.user.verifyCodeKey = codeKey
                $scope.user.verifyCodeUrl = AuthService.getRsContext() + "/rest/verifycode/image?verifyKey=" + codeKey;
                //test code ===========
                //$scope.user.verifyCode = codeKey;
                //$scope.user.password = "zhangyi";
                console.log('login ==== verifyCodeKey=', codeKey);
            }
        };
        var initCookie = function () {
            var username = $window.localStorage.getItem(cookieNameKey);
            $scope.user.username = username;
            if (username && username != "") {
                $scope.user.rememberme = true;
            }
        };

        var getNeedKey = function () {
            var cookieNeedNameKey = "_userName_NeedKey_"
            var needKey = $window.localStorage.getItem(cookieNeedNameKey);
            if (needKey == null || needKey == "") {
                needKey = "";
                for (var i = 0; i < codeLength; i++) {
                    var index = Math.floor(Math.random() * 34);
                    needKey += random[index];
                }
                $window.localStorage.setItem(cookieNeedNameKey, needKey);
            }
            return needKey;
        }

        var init = function () {
            initVerifyCode();
            initCookie();

            // check need verify code
            var needKey = getNeedKey();
            $http({
                method: "GET",
                url: AuthService.getRsContext() + "/rest/verifycode/needVerifyCode?verifyKey=" + needKey
            }).then(function successCallback(data1) {
                if (data1.data.code == 0) {
                    $scope.needVerifyCode = data1.data.data[0].need;
                }
            });

            // check version
            var oldversion = appinfo.version;
            var newversion = '';
            $http({
                method: "GET",
                url: appinfo.infourl
            }).then(function successCallback(data1) {
                console.log("checkApkVersion", data1);
                newversion = data1.data[0].apkversion;
                if (newversion > oldversion) {
                    $scope.hasNewVersion = true;
                    $scope.apkurl = appinfo.apkurl + '/' + appinfo.apkname;
                }
            });
        };
        init();
    }]);
